<?php
/*
 * 后台模块树
 * author wangjian
 * time 2013-05-18
 *
 */
if (! defined('BASEPATH')) {
	exit('Access Denied');
}

class Tree extends MY_Controller{
	private $username ;//当前登录的用户
	private $ip ; //登录的ip地址
	private $dir = './data/tree'; //生成的xml文件路径
	private $table_ ; //表的前缀
	
	function Tree(){
		parent::__construct();
		$this->load->library('admin_common');//加载admin的公用方法
		$this->load->model('admin/tree/M_tree');
		date_default_timezone_set('Asia/Shanghai');
		$this->load->model('admin/M_log');//加载日志模型
		$this->username = $this->get_login_name(); //得到登录的用户名
		$this->ip = $this->admin_common->get_client_ip();
		$this->table_ = $this->admin_common->table_pre('real_data');
	}
	
	function tree_list(){
	
		$data_ = $_REQUEST ;
		$action = 'tree_list' ;
		$action_array = array(
			'tree_list','tree_list_add_do'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'tree_list';
		if($action == 'tree_list_add_do'){
			$this->tree_list_add_do() ;
			exit();
		}elseif($action == 'tree_list'){
			$post_data = $this->input->post(NULL,true) ;		
		
			$sql_type = "SELECT id,typename from {$this->table_}common_tree_type order by id desc ";
			$res_type = $this->M_tree->querylist($sql_type,false);
			$result = array();
			if($res_type){
				foreach($res_type as $res_key=>$res_val){
					$result[$res_val['id']] = $res_val['typename'];
				}
			}
			$tree_type_array = $result ;
		
			$tree_type = '' ;//模块树类别 。
			
			if(isset($post_data['tree_type'])){
				
				$tree_type = intval($post_data['tree_type']);
				
			}else{
				$tree_type = 1 ;
			}
			
			$page = 1 ;
			$page_num = 10 ; //每一页显示的数量
			if(isset($_REQUEST['p']) && $_REQUEST['p'] != ''){
				$page = intval($_REQUEST['p']);
			}
			$limit = '' ;
			$n = ($page - 1 )*$page_num;
			$limit =" LIMIT {$n},$page_num" ;
			$total = $this->M_tree->query_count("SELECT COUNT(*) AS tt FROM `{$this->table_}common_tree` WHERE tree_parent_id=0  AND tree_type = '{$tree_type}'");
			
			$page_string = $this->page_string($total, $page_num, $page);
			
			$res = $this->M_tree->queryparenttree($tree_type,$limit);
			$s = '' ;
			
			if(isset($_GET['s']) && $_GET['s'] != ""){
								
				echo $this->admin_common->result_to_towf_new($res,1,'',$page_string);
			}else{
				$data['type_array'] = $tree_type_array ;
				$this->load->view('admin/tree/views_tree_list',$data);
			}
		}	
	}
	
	//添加模块树进行处理
	private function tree_list_add_do(){
		
		$tree_type_array =$this->admin_common->return_treetype_list();
		$post_data = $this->input->post(NULL,true) ;
		
		$tree_name = '' ;
		$tree_name = html_escape($this->admin_common->do_addslashes(trim($post_data['tree_name'])));
		
		$id = intval($post_data['id']) ;
		$code = 1 ;
		$message = '' ;
		if(empty($tree_name)){
			$code = 0 ;
			$message = '模块名称不可以是空' ;
			echo $this->admin_common->result_to_towf_new('',$code,$message,null);
			return false ;
		}
		
		
		$new_tree_type = intval($post_data['tree_type']);
		
		$data_insert = array();
		$data_insert = array(
				'tree_parent_id'=>$id ,
				'tree_name'=>$tree_name,
				'tree_type'=>$new_tree_type,
				'tree_orderby'=>intval($post_data['tree_orderby']),
		);
	
		$result_array = $this->M_tree->insert_one($data_insert);
		if($result_array[0]>=1){
			$code = 1 ;
			$message = '插入成功' ;
			
			$this->M_log->insert($result_array[1],'log_add_tree',$this->username,$this->ip,1,"添加模块树{$tree_name}类别是{$new_tree_type}成功"); //插入日志记录
		}else{
			$code = '0' ;
			$message = '服务器繁忙请稍后';
			$this->M_log->insert($result_array[1],'log_add_tree',$this->username,$this->ip,0,"添加模块树{$tree_name}类别是{$new_tree_type}失败"); //插入日志记录
		}
		echo $this->admin_common->result_to_towf_new('',$code,$message,null);
		
		
	}
	
	//修改模块树页面
	function tree_edit(){
		$data_ = $_REQUEST ;
		$action = 'tree_edit' ;
		$action_array = array(
			'tree_edit','tree_edit_do'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'tree_edit';
		if($action == 'tree_edit'){
			if(isset($_GET['id'])){
				$id = intval($_GET['id']);
			}else{
				$id = $_GET['id'];
			}
			$sql = "SELECT `tree_id`,`tree_parent_id`,`tree_name`,`tree_type`,`tree_orderby` FROM `{$this->table_}common_tree` WHERE `tree_id` = '{$id}'" ;
			
			$one = $this->M_tree->query_one($sql);
			$data=array(
					'one'=>$one,
					
			);
			
			$this->load->view('admin/tree/views_tree_edit',$data);
		}elseif($action == 'tree_edit_do'){
			$this->tree_edit_do() ;
		}
		
	}
	//修改模块树处理
	private function tree_edit_do(){
		$post_data = $this->input->post(NULL,true) ;
		$tree_id = intval($post_data['tree_id']);
		$tree_name = html_escape($this->admin_common->do_addslashes(trim($post_data['tree_name'])));
		$tree_orderby = intval($post_data['tree_orderby']);
		$code = 1 ;
		$message = '' ;
		if(empty($tree_name)){
			$code = 0 ;
			$message = '模块名称不可以是空' ;
			echo $this->admin_common->result_to_towf_new('',$code,$message,null);
			return false ;
		}
		$sql_update = "UPDATE `{$this->table_}common_tree` SET `tree_name` = '{$tree_name}',`tree_orderby` = '{$tree_orderby}' WHERE tree_id='{$tree_id}'" ;	
		
		$num = $this->M_tree->update_data($sql_update);	
		if($num>=1){
			$code = 1 ;
			$message = '修改成功' ;
			$this->M_log->insert($sql_update,'log_update_tree',$this->username,$this->ip,1,"修改模块树为{$tree_name}成功"); //插入日志记录
		}else{
			$code = '0' ;
			$message = '服务器繁忙请稍后';
			$this->M_log->insert($sql_update,'log_update_tree',$this->username,$this->ip,0,"修改模块树为{$tree_name}失败"); //插入日志记录
		}
		echo $this->admin_common->result_to_towf_new('',$code,$message,null);
		die();
	}
	
	//删除模块树处理
	function tree_del_do(){
		$post_data = $this->input->post(NULL,true) ;
		$id = intval($post_data['id']);
		$sql="DELETE FROM `{$this->table_}common_tree` WHERE (`tree_id` = '{$id}' or tree_parent_id='{$id}')";
		$num = $this->M_tree->del_data($sql);
		$code = 0 ;
		$message = '' ;
		if($num>=1){
			$code = 1 ;
			$message = '删除成功';
			$this->M_log->insert($sql,'log_delete_tree',$this->username,$this->ip,1,"删除模块树{$id}成功"); //插入日志记录
		}else{
			$code = 0 ;
			$message= '服务器繁忙，或者地址出错' ;
			$this->M_log->insert($sql,'log_delete_tree',$this->username,$this->ip,0,"删除模块树{$id}失败，可能服务器繁忙，或者地址出错"); //插入日志记录
		}
		echo $this->admin_common->result_to_towf_new('',$code,$message,null);
		return ;
	}
	//生成数据文件（模块树）
	function make_xml(){
		
		$post_data = $_REQUEST;
		$action = 'tree_make' ;
		$action_array = array(
			'tree_make','tree_type_make'
		) ;
		
		$action = (isset($post_data['action']) && in_array($post_data['action'], $action_array))?$post_data['action']:'tree_make';
		
		if($action == 'tree_make'){
			$tree_type = intval(isset($post_data['tree_type'])?$post_data['tree_type']:0);
			$sql="SELECT * FROM `{$this->table_}common_tree` WHERE `tree_type` = '{$tree_type}'";
			$data_list = $this->M_tree->querylist($sql);
			$res = '' ;
			if($data_list){
				$data_list = $this->admin_common->object_to_array($data_list);
				$res = $this->genCate($data_list);
			}
			
			$res_tree = $this->M_tree->queryparenttree($tree_type);
			
			$code = 0 ; //默认是 0
			$message = '' ;//提示信息
		
			
			if(empty($res)){
				$code = 0 ;
				$message = '对不起没有模块树数据';
				echo $this->admin_common->result_to_towf_new('',$code,$message,null);
				return ;
			}else{
								
				$str = serialize($res);
				if(!is_really_writable("{$this->dir}")){
				
					$code = 0 ;
					$message = "对不起目录{$this->dir}不可写,请保证有可写的权限" ;
					echo $this->admin_common->result_to_towf_new('',$code,$message,null);
					return ;
				}
				//@file_put_contents("{$this->dir}/tree_{$tree_type}.txt", $str);
				@file_put_contents("{$this->dir}/tree_{$tree_type}_format.txt", serialize($res_tree));
				$code = 1 ;
			}
	
	
			echo $this->admin_common->result_to_towf_new(array('dir'=>$this->dir),$code,$message,null);
			return '';		
		}elseif($action == 'tree_type_make'){
			$this->make_tree_type_cache();
		}

	}
//生成模块树缓存
private  function make_tree_type_cache(){
	set_time_limit(0);
	$post_data = $_REQUEST ;
	$tree_type = (isset($post_data['make_id'])?$post_data['make_id']:0);
	if(!$tree_type){
		exit('params is error');
	}
	$array = explode(",",$tree_type);
	for($k = 0 ;$k<count($array);$k++){
		$data_list = $this->M_tree->queryparenttree(intval($array[$k]));
		if(!is_really_writable("{$this->dir}")){
			$message = "目录{$this->dir}没有可写的权限" ;
		}else{
			@file_put_contents("{$this->dir}/tree_{$array[$k]}_format.txt", serialize($data_list));
			$message = "正在生成模块树是{$this->dir}/<font color='red'>tree_{$array[$k]}_format.txt</font>的文件" ;
		}
		
		$this->echo_now($message);
	}

	
}
//及时输出函数

private function echo_now($msg){
	@ob_start();
	@ob_end_clean();
	echo str_repeat(" ",1024);
	echo date('H:i:s').'='.$msg,"<hr color='#D1DDAA'>";
	echo '<script>window.scrollTo(0,document.body.offsetHeight+document.body.scrollTop)</script>';
	@ob_flush();
	@flush();
	usleep(100000);
} 	
	
private function genCate($data, $pid = 0, $level = 0) 
{ 
    if($level == 10) break; 
    static $tarr= array(); 
    $l    = str_repeat("&nbsp;", $level); 
    $l    = $l.'└'; 
    foreach($data as $row) 
    { 
        /** 
         * 如果父ID为当前传入的id  www.mb5u.com 
         */ 
        if($row['tree_parent_id'] == $pid) 
        { 
            //如果当前遍历的id不为空 
            $row['tree_name']    = htmlspecialchars($l.$row['tree_name']); 
            $row['level']    = $level; 
            $tarr[]    = $row; 
            $this->genCate($data, $row['tree_id'], $level+1);//递归调用 
        } 
    } 
    return $tarr; 
}
	
	/*@function page_string
	 *@分页返回数据
	 *@total 总的数量
	 *@page_num 每一页显示的数量
	 *@page 当前是第几页数据
	 */
	private function page_string($total,$page_num,$page){
		$page_string = '' ;
		$this->load->library('pagination');//加载分页类
		$this->load->library('MY_Pagination');//加载分页类
		$config['total_rows'] = $total;
		$config['use_page_numbers'] =true; // 当前页结束样式
		$config['per_page'] = $page_num; // 每页显示数量，为了能有更好的显示效果，我将该数值设置得较小
		$config['full_tag_open'] = '<div class="pg">'; // 分页开始样式
		$config['full_tag_close'] = '</div>'; // 分页结束样式
		$config['first_link'] = '首页'; // 第一页显示
		$config['last_link'] = '末页'; // 最后一页显示
		$config['next_link'] = '下一页 >'; // 下一页显示
		$config['prev_link'] = '< 上一页'; // 上一页显示
		$config['cur_tag_open'] = ' <a class="current">'; // 当前页开始样式
		$config['cur_tag_close'] = '</a>'; // 当前页结束样式
		$config['uri_segment'] = 6;
		$config['anchor_class']='class="ajax_page" ';
		$this->pagination->cur_page = $page ;
		$this->pagination->initialize($config); // 配置分页
		$page_string =  $this->pagination->create_links(true,'ajax_data');
		return $page_string ;
	}	
}


















